package game.systems.spatial.verticalDepth
{
	import ash.core.Engine;
	import ash.core.NodeList;
	import ash.core.System;
	
	import engine.classes.enumerations.SystemPriority;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	
	
	/**
	 * The Top Down Depth System manages the layering of DisplayObjects in a common parent Display Object Container
	 * based on the index and Y comparisons between 2 TopDownDepthNodes. This gives a game a Pokemon-style top-down
	 * feel, where objects closer to the bottom of the screen are "in front" of objects above and "behind" them.
	 */
	public class VerticalDepthSystem extends System
	{
		private var nodes:NodeList;
		
		public function VerticalDepthSystem()
		{
			this.priority = SystemPriority.POST_RENDER;
		}
		
		override public function update(time:Number):void
		{
			for(var node1:VerticalDepthNode = this.nodes.head; node1; node1 = node1.next)
			{
				var index1:int = node1.render.display.parent.getChildIndex(node1.render.display);
				var y1:Number;
				
				switch(node1.depth.type)
				{
					case VerticalDepth.DISPLAY: y1 = node1.render.display.y; 	break;
					case VerticalDepth.SPATIAL: y1 = node1.spatial.y; 			break;
				}
				
				for(var node2:VerticalDepthNode = node1.next; node2; node2 = node2.next)
				{
					if(node1.render.display.parent != node2.render.display.parent) continue;
					
					var index2:int = node2.render.display.parent.getChildIndex(node2.render.display);
					var y2:Number;
					
					switch(node2.depth.type)
					{
						case VerticalDepth.DISPLAY: y2 = node2.render.display.y; 	break;
						case VerticalDepth.SPATIAL: y2 = node2.spatial.y; 			break;
					}
					
					if(y1 > y2 && index1 < index2)
						node1.render.display.parent.setChildIndex(node1.render.display, index2);
					
					else if(y2 > y1 && index2 < index1)
						node1.render.display.parent.setChildIndex(node2.render.display, index1);
				}
			}
		}
		
		override public function addToEngine(systemManager:Engine):void
		{
			this.nodes = systemManager.getNodeList(VerticalDepthNode);
		}
		
		override public function removeFromEngine(systemManager:Engine):void
		{
			systemManager.releaseNodeList(VerticalDepthNode);
			
			this.nodes = null;
		}
	}
}